﻿using System;
using System.ServiceModel;
using System.Web;
using NhJump.Persistence.Context.HttpContextBinding;
using NhJump.Persistence.Context.ThreadLocalBinding;
using NhJump.Persistence.Context.WcfBinding;

namespace NhJump.Persistence.Context
{
    public static class UnitOfWorkBinder
    {
        private static IUnitOfWorkBinder GetCurrentBinder()
        {
            if (OperationContext.Current != null)
            {
                return new WcfUnitOfWorkBinder();
            }

            if (HttpContext.Current != null)
            {
                return new HttpContextUnitOfWorkBinder();
            }

            return new ThreadLocalPersistenceBinder();
        }

        public static UnitOfWork CurrentUnitOfWork
        {
            get
            {
                return GetCurrentBinder().GetCurrent();
            }
        }

        public static void Bind(UnitOfWork unitOfWork)
        {
            if (CurrentUnitOfWork != null)
                throw new Exception("A UnitOfWork is already bound");

            GetCurrentBinder().Bind(unitOfWork);
        }

        public static void UnBind()
        {
            GetCurrentBinder().UnBind();
        }
    }
}
